using MultiAgentsShared;
using static MultiAgentsClient.Manager.AgentManager;
using static MultiAgentsClient.Presentation.AgentListModel;

namespace MultiAgentsClient.Presentation;

public partial record ShareAgentPopupModel
{
    private readonly IEventBus eventBus;

    public IState<string> AgentJsonInput => State.Value(this, () => "");
    public IState<bool> IsPopupOpen => State.Value(this, () => false);

    public ShareAgentPopupModel()
    {
        eventBus = EventBus.Instance;

        eventBus.Subscribe<LoadAgentByShareCodeClickCommand>(async cmd => { await LoadAgentByShareCodeCommandHandler(); });
    }

    public async Task LoadAgentByShareCodeCommandHandler()
    {
        await IsPopupOpen.SetAsync(true);
    }

    public async ValueTask Close()
    {
        await IsPopupOpen.SetAsync(false);
    }

    public async Task LoadAgentByJson()
    {
        string? AgentJson = await AgentJsonInput;
        if (string.IsNullOrWhiteSpace(AgentJson))
        {
            return;
        }

        try
        {
            AgentTemplate agentTemplate = SerializableObjectBase.FromJson<AgentTemplate>(AgentJson);
        }
        catch (Exception)
        {
            Debug.LogWindow("json格式错误。");
            return;
        }

        eventBus.Publish(new LoadAgentByShareCodeCommand(AgentJson));
        await AgentJsonInput.SetAsync("");
        await IsPopupOpen.SetAsync(false);
    }
}
